package pub.cleangao.memm.registry;


import lombok.Data;
import pub.cleangao.memm.util.PropertiesLoader;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;


@Data
public class RpcConfigProperties {


    static final String CONFIG_PROPERTIES = "rpc.properties";

    public static RpcConfigProperties init() {
        Properties properties = PropertiesLoader.loadFrom(CONFIG_PROPERTIES);
        if (properties != null) {
            RpcConfigProperties configProperties = new RpcConfigProperties();
            configProperties.setPort(Integer.parseInt(properties.getProperty("rpc.server.port", "9999")));
            String bindIp = properties.getProperty("rpc.server.bind_ip", "");
            configProperties.setBindIp(bindIp.trim());
            String registryTypeStr = properties.getProperty("rpc.registry.type", "");
            RegistryType registryType = RegistryType.from(registryTypeStr.trim().toLowerCase());
            configProperties.setRegistryType(registryType);
            String registryUrl = properties.getProperty("rpc.registry.url", "");
            configProperties.setRegistryUrl(registryUrl.trim());
            String registryUsername = properties.getProperty("rpc.registry.username", null);
            configProperties.setRegistryUsername(registryUsername);
            String registryPassword = properties.getProperty("rpc.registry.password", "");
            configProperties.setRegistryPassword(registryPassword.trim());
            setDefaultValues(configProperties);
            return configProperties;
        }
        throw new RuntimeException("Classpath not found config file: rpc.properties");
    }

    private static void setDefaultValues(RpcConfigProperties properties) {
        if (properties.getBindIp() == null || properties.getBindIp().isBlank()) {
            try {
                properties.setBindIp(InetAddress.getLocalHost().getHostAddress());
            } catch (UnknownHostException ignore) {
            }
        }
        if (properties.getRegistryType() == null) {
            properties.setRegistryType(RegistryType.ETCD);
        }
    }

    /**
     * 端口号
     */
    private int port;

    /**
     * 是否绑定IP
     */
    private String bindIp;


    /**
     * 注册中心类型
     */
    private RegistryType registryType;

    /**
     * server:port 使用英文逗号分割
     */
    private String registryUrl;

    /**
     * 注册中心密码
     */
    private String registryPassword;


    private String registryUsername;


}
